# -*- coding:utf-8 -*-
from tornado import gen
from appcommon.appinstance import mysql_app_pool
from common import timetool
from pay import models as paym
import requests
from settings import PAY_TYPE
from xml.etree import ElementTree


def create_response_text(fromusername, tousername, msgtype, content):
    xml_tpl = u"""<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            </xml>"""
    out = xml_tpl % (fromusername, tousername, timetool.get_current_timestamp(), msgtype, content)
    return out


def create_response(fromusername, tousername):
    xml_tpl = u"""<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[news]]></MsgType>
    <ArticleCount>%s</ArticleCount>
    <Articles>
    %s
    </Articles>
    </xml>"""
    article_tpl = u"""
    <item>
    <Title><![CDATA[{}]]></Title>
    <Description><![CDATA[{}]]></Description>
    <PicUrl><![CDATA[{}]]></PicUrl>
    <Url><![CDATA[{}]]></Url>
    </item>
    """
    article_list = [
        dict(title=u"启程驾考公司简介", desc="", pic="http://app.qcjkjg.com/media/img/wechat/wechat1.jpg", url="http://mp.weixin.qq.com/s/V5Apt9lXTef1sxViWdF24g"),
        dict(title=u"第一步：教练认证入驻", desc="", pic="http://app.qcjkjg.com/media/img/wechat/wechat2.jpg", url="http://mp.weixin.qq.com/s/wIsj56M1rUXcMOgD8i9Hzw"),
        dict(title=u"第二部：教练邀请学员", desc="", pic="http://app.qcjkjg.com/media/img/wechat/wechat3.jpg", url="http://mp.weixin.qq.com/s/9jxE7f34tUGb60P4v01pTQ"),
        dict(title=u"教练名片制作介绍", desc="", pic="http://app.qcjkjg.com/media/img/wechat/wechat4.jpg", url="http://mp.weixin.qq.com/s/Ya-2QAXZLT12DAk9ljwieg"),
    ]
    article_str = ""
    for item in article_list:
        article_str += article_tpl.format(item['title'], item['desc'], item['pic'], item['url'])

    out = xml_tpl % (fromusername, tousername, timetool.get_current_timestamp(), len(article_list), article_str)
    return out


@gen.coroutine
def get_money_with_ex_code(ex_code):
    sql = (
        "select * from app_red where ex_code='{}'"
    )
    res = yield mysql_app_pool.get_one(sql.format(ex_code), cursor='dict')
    raise gen.Return(res['money'])


@gen.coroutine
def send_red_to_phone(phone, money):
    open_id = yield get_gzh_open_id_with_phone(phone)
    if open_id:
        res = yield send_red_to_wx(open_id, money)
    else:
        res = 2
    raise gen.Return(res)


@gen.coroutine
def send_red_to_wx(open_id, money):
    trada_info = PAY_TYPE['gzh']
    nonce_str = paym.getnonce_str()
    # 签名时用到的字典
    param_dic = {
         'wxappid': trada_info["appid"],
         'mch_id': trada_info["mch_id"],
         'nonce_str': nonce_str,
         'mch_billno': nonce_str,
         'send_name': u"启程驾考交规",
         're_openid': open_id,
         'total_amount': str(int(100*float(money))),
         'total_num': '1',
         'wishing': u"感谢您使用启程驾考交规",
         'client_ip': "47.92.112.59",
         'act_name': u"启程驾考交规分享",
         'remark': "456",
         'scene_id': "PRODUCT_1"
     }
    signStr = paym.creatsig_md5(param_dic, trada_info["signkey"])
    # signStr = paym.creatsig_md5(param_dic, "qichengjiakaojiaogui2017")
    # 向微信服务器发送的xml文档

    xmlData = '''<xml>
    <wxappid>''' + param_dic['wxappid'] + '''</wxappid>
    <mch_id>''' + param_dic['mch_id'] + '''</mch_id>
    <nonce_str>''' + param_dic['nonce_str'] + '''</nonce_str>
    <mch_billno>''' + param_dic['mch_billno'] + '''</mch_billno>
    <send_name>''' + param_dic['send_name'] + '''</send_name>
    <re_openid>''' + param_dic['re_openid'] + '''</re_openid>
    <total_amount>''' + param_dic['total_amount'] + '''</total_amount>
    <total_num>''' + param_dic['total_num'] + '''</total_num>
    <wishing>''' + param_dic['wishing'] + '''</wishing>
    <client_ip>''' + param_dic['client_ip'] + '''</client_ip>
    <act_name>''' + param_dic['act_name'] + '''</act_name>
    <remark>''' + param_dic['remark'] + '''</remark>
    <scene_id>''' + param_dic['scene_id'] + '''</scene_id>
    <sign>''' + signStr + '''</sign>
    </xml>'''
    xmlresult = requests.post("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack", data=xmlData.encode('utf-8'),
                              cert=(
                                  "/home/qic/Qc_App_Server/apiclient_cert.pem",
                                  "/home/qic/Qc_App_Server/apiclient_key.pem",
                              ))
    xdict = xmltodict(xmlresult.text)
    return xdict


def xmltodict(xmlstr):
    root = ElementTree.fromstring(xmlstr.encode('utf-8'))
    return_code = root.find('return_code')
    result_code = root.find('result_code')
    if return_code.text == 'SUCCESS' and result_code.text == 'SUCCESS':
        return 1
    else:
        return 0


@gen.coroutine
def get_gzh_open_id_with_phone(phone):
    sql = (
        "select open_id from wx_bind where phone = '{}'"
    )
    info = yield mysql_app_pool.get_one(sql.format(phone), cursor='dict')
    res = info['open_id'] if info else ""
    raise gen.Return(res)
